﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.ComponentModel;

namespace RL
{
    /// <summary>
    /// Логика взаимодействия для wVehicle.xaml
    /// </summary>
    public partial class wVehicle : Window
    {



        public vehicle vehicle
        {
            get { return (vehicle)GetValue(vehicleProperty); }
            set { SetValue(vehicleProperty, value); }
        }

        // Using a DependencyProperty as the backing store for vehicle.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty vehicleProperty =
            DependencyProperty.Register("vehicle", typeof(vehicle), typeof(wVehicle), new UIPropertyMetadata(null, new PropertyChangedCallback(propVehicle)));

        public static void propVehicle(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            wVehicle item = d as wVehicle;
            if (null == item) return;
            vehicle it = e.NewValue as vehicle;
            if (null == it) return;
            //System.Windows.Data.CollectionViewSource vehicleViewSource = ((System.Windows.Data.CollectionViewSource)(item.FindResource("vehicleViewSource")));
            item.vehicleDataGrid.SelectedItem = it;
            item.vehicleDataGrid.ScrollIntoView(it);
        }

        public routelistEntities ContextDB
        {
            get { return (routelistEntities)GetValue(ContextDBProperty); }
            set { SetValue(ContextDBProperty, value); }
        }

        // Using a DependencyProperty as the backing store for ContextDB.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty ContextDBProperty =
            DependencyProperty.Register("ContextDB", typeof(routelistEntities), typeof(wVehicle), new UIPropertyMetadata(null));



        public int VehicleID
        {
            get { return (int)GetValue(VehicleIDProperty); }
            set { SetValue(VehicleIDProperty, value); }
        }

        // Using a DependencyProperty as the backing store for VehicleID.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty VehicleIDProperty =
            DependencyProperty.Register("VehicleID", typeof(int), typeof(wVehicle), new UIPropertyMetadata(0, new PropertyChangedCallback(propVehicleID)));

        public static void propVehicleID(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            wVehicle item = d as wVehicle;
            if (null == item) return;
            int val = (int)e.NewValue;
            if (null == item.ContextDB) return;
            item.vehicle = (from o in item.ContextDB.vehicle where o.id == val select o).FirstOrDefault();
        }


        public wVehicle()
        {
            InitializeComponent();
            if (System.ComponentModel.DesignerProperties.GetIsInDesignMode(this)) return;
            ContextDB = new routelistEntities();
        }

        private void CreateNew()
        {
            if (null == ContextDB) return;
            vehicle item = new vehicle();
            vehicle_type vtype = (from o in ContextDB.vehicle_type orderby o.name select o).FirstOrDefault();
            if (null == vtype) return;
            item.id_type = vtype.id;
            item.gar_number = "";
            item.gos_number = "";
            item.name_type = vtype.name;
            item.id_main_fuel_type = vtype.id_main_fuel_type;
            item.type_vehicle = vtype.type_vehicle;
            item.heater = vtype.heater;
            item.lid_main_fuel_type = false;
            item.ltype_vehicle = false;
            item.lfueltype = false;
            item.kind_license_card = 1;
            item.license_reg_number = "";
            item.license_number = "";
            item.qnt_passenger = 0;
            item.qnt_total_passenger = 0;
            item.del = false;
        }

        private System.Data.Objects.ObjectQuery<vehicle> GetvehicleQuery(routelistEntities routelistEntities)
        {
            // Автоматически созданный код

            System.Data.Objects.ObjectQuery<RL.vehicle> vehicleQuery = routelistEntities.vehicle;
            // Для явной загрузки данных, возможно, потребуется добавить методы Include, аналогичные показанным ниже:
            // vehicleQuery = vehicleQuery.Include("vehicle.fuel_type").
            // Дополнительные сведения см. по ссылке http://go.microsoft.com/fwlink/?LinkId=157380
            // Возвращает ObjectQuery.
            return vehicleQuery;
        }

        private System.Data.Objects.ObjectQuery<RL.vehicle_type> GetvehicleTypeQuery(routelistEntities routelistEntities)
        {
            System.Data.Objects.ObjectQuery<RL.vehicle_type> vehicleTypeQuery = routelistEntities.vehicle_type.OrderBy("it.name");
            return vehicleTypeQuery;
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {

            RL.routelistEntities routelistEntities;
            if (null == ContextDB)
                routelistEntities = new RL.routelistEntities();
            else
                routelistEntities = ContextDB;
            // Загрузить данные в vehicle. Можно изменить этот код как требуется.
            System.Windows.Data.CollectionViewSource vehicleViewSource = ((System.Windows.Data.CollectionViewSource)(this.FindResource("vehicleViewSource")));
            System.Data.Objects.ObjectQuery<RL.vehicle> vehicleQuery = this.GetvehicleQuery(routelistEntities);
            vehicleViewSource.Source = vehicleQuery.Execute(System.Data.Objects.MergeOption.AppendOnly);

            System.Windows.Data.CollectionViewSource vehicleTypeViewSource = (System.Windows.Data.CollectionViewSource)(this.Resources["vehicleTypeViewSource"]);
            System.Data.Objects.ObjectQuery<RL.vehicle_type> vehicleTypeQuery = GetvehicleTypeQuery(routelistEntities);
            vehicleTypeViewSource.Source = vehicleTypeQuery.Execute(System.Data.Objects.MergeOption.AppendOnly);
        }

        private void buttonSave_Click(object sender, RoutedEventArgs e)
        {
            SaveData();
        }

        private void buttonAdd_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Data.CollectionViewSource vehicleViewSource = ((System.Windows.Data.CollectionViewSource)(this.FindResource("vehicleViewSource")));
            vehicle item = ((IEditableCollectionView)(vehicleViewSource.View)).AddNew() as vehicle;
            if (null == ContextDB) return;
            vehicle_type vtype = (from o in ContextDB.vehicle_type orderby o.name select o).FirstOrDefault();
            if (null == vtype) return;
            item.id_type = vtype.id;
            item.gar_number = "";
            item.gos_number = "";
            item.name_type = vtype.name;
            item.id_main_fuel_type = vtype.id_main_fuel_type;
            item.type_vehicle = vtype.type_vehicle;
            item.heater = vtype.heater;
            item.lid_main_fuel_type = false;
            item.ltype_vehicle = false;
            item.lfueltype = false;
            item.kind_license_card = 1;
            item.license_reg_serial = "";
            item.license_reg_number = "";
            item.license_number = "";

            item.qnt_passenger = 0;
            item.qnt_total_passenger = 0;
            item.del = false;
            ((IEditableCollectionView)(vehicleViewSource.View)).CommitNew();
        }

        private void buttonOK_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Data.CollectionViewSource vehicleViewSource = ((System.Windows.Data.CollectionViewSource)(this.FindResource("vehicleViewSource")));
            vehicle = vehicleViewSource.View.CurrentItem as vehicle;
            try
            {
                DialogResult = true;
            }
            catch (Exception)
            {
            }
        }

        private bool IsModified()
        {
            bool bResult = false;
            if (null == ContextDB) return false;
            bResult = ContextDB.ObjectStateManager.GetObjectStateEntries(System.Data.EntityState.Added).Count() > 0 || ContextDB.ObjectStateManager.GetObjectStateEntries(System.Data.EntityState.Deleted).Count() > 0 || ContextDB.ObjectStateManager.GetObjectStateEntries(System.Data.EntityState.Modified).Count() > 0;
            return bResult;
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (IsModified())
            {
                var result = MessageBox.Show("Сохранить изменения?", "Предупреждение", MessageBoxButton.YesNoCancel, MessageBoxImage.Exclamation, MessageBoxResult.Yes);
                switch (result)
                {
                    case MessageBoxResult.Yes:
                        if (false == SaveData())
                        {
                            e.Cancel = true;
                        }
                        break;
                    case MessageBoxResult.Cancel:
                        e.Cancel = true;
                        break;
                }

            }
        }

        private bool SaveData()
        {
            bool bResult = true;
            try
            {
                ContextDB.SaveChanges();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), Properties.Resources.DataSavingError, MessageBoxButton.OK, MessageBoxImage.Exclamation);
                bResult = false;
            }
            return bResult;
        }
    }
}
